package cc.dawning.utiming.lklocation.location.utils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Environment;
import android.util.Log;
import android.view.View;

import cc.dawning.utiming.lklocation.location.global.FileKey;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


/**
 * Date 2018/3/27
 * Describe 截屏并保存文件
 *
 * @auther liuxin
 */

public class SaveScreenUtils {

    public static File saveScreen(View v) {
        File f1 = null;
        v.setDrawingCacheEnabled(true);
        v.buildDrawingCache();
        Bitmap bitmap = v.getDrawingCache();
        if (null != bitmap) {
            File file = new File(FileKey.PATH_SCREEN_LOCATION);
            if (!file.exists()) {
                file.mkdirs();
            }
            f1 = new File(file, System.currentTimeMillis() + "screen.png");
            Log.e("截屏地址=====", f1.getAbsolutePath());
            if (!f1.exists()) {
                try {
                    f1.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileOutputStream fot = null;
            try {
                fot = new FileOutputStream(f1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fot);
            try {
                fot.flush();
                fot.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return f1;
    }

    /**
     * 生成视图的预览
     * @param activity
     * @param v
     * @return  视图生成失败返回null
     *          视图生成成功返回视图的绝对路径
     */
    public static File saveImage(Activity activity, View v) {
        Bitmap bitmap;
        String path =  Environment.getExternalStorageDirectory().getAbsolutePath()  + "screen.png";
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        bitmap = view.getDrawingCache();
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        try {
            bitmap = Bitmap.createBitmap(bitmap, location[0], location[1], v.getWidth(), v.getHeight());
            FileOutputStream fout = new FileOutputStream(path);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fout);
            return new File(path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.e("截屏", "生成预览图片失败：" + e);
        } catch (IllegalArgumentException e) {
            Log.e("截屏", "width is <= 0, or height is <= 0");
        } finally {
            // 清理缓存
            view.destroyDrawingCache();
        }
        return null;

    }
}
